﻿using System;
using System.IO;
using System.Linq;
using System.Web;
using SlamCms.Common;

namespace SlamCms.Web.Mvc
{
	public class EmbeddedResourceFileResult : ExtendedFileStreamResult
	{
		public EmbeddedResourceFileResult(string name, string contentType = null)
			: base(GetEmbeddedResourceStream(name), contentType ?? MimeTypeHelpers.GetFromFileName(name))
		{
			this.SetEtag(this.GenerateETag(name));
			this.SetNoContentTypeSniffing();
		}

		private static Stream GetEmbeddedResourceStream(string name)
		{
			// TODO cache this
			Stream stream = null;

			foreach (var assembly in TypeHelpers.GetNonSystemAssemblies())
			{
				try
				{
					var fullName = assembly.GetManifestResourceNames().FirstOrDefault(x => x.EndsWith(name));

					if (!fullName.IsNullOrWhiteSpace())
					{
						stream = assembly.GetManifestResourceStream(fullName);
						break;
					}
				}
				catch (Exception)
				{
					// an exception is not fatal... continue
				}
			}

			if (stream == null)
				throw new HttpException(404, "Cannot find resource name {0}".F(name));

			return stream;
		}
	}
}
